<template>
  <a-upload
    v-model:file-list="fileList"
    :action="action"
    :data="dataCallback"
    :headers="headers"
    :showUploadList="false"
    multiple
    @change="onChange"
    :beforeUpload="onBeforeUpload"
    ref="uploadLocalRef"
  >
    <div style="display: flex" @click="onClick" id="upload-local">
      <slot>本地上传</slot>
    </div>
  </a-upload>
</template>
<script setup>
import { ref, toRaw } from 'vue'
import {
  usePublishCount,
  useUploadLocalFileList,
  useGroupId,
  useDataSourceManager,
  useUploadLocalRef,
  usePublishDrawerContentKey,
} from './provide-context.js'
import { message as Message } from 'ant-design-vue'
import { useAccountStore } from '@/stores/account'
import { storeToRefs } from 'pinia'
import { rewriteURL } from '@/api/db.js'
import { useDbType } from './provide-context.js'
/**
 * 入参
 */
let props = defineProps({ params: { type: Object, default: () => ({}) } })
/**
 * 事件定义
 */
let emit = defineEmits(['end', 'start'])
/**
 * 全局
 */
let publishCount = usePublishCount()
let fileList = useUploadLocalFileList()
let groupId = useGroupId()
let { update } = useDataSourceManager()
let uploadLocalRef = useUploadLocalRef()
let publishDrawerContentKey = usePublishDrawerContentKey()
/**
 * 用户信息
 */
let accountStore = useAccountStore()
let account = storeToRefs(accountStore)
/**
 * 交互
 */
let loading = ref(false)
function onBeforeUpload(file) {
  let filename = file.name || ''
  if (filename.includes('.')) {
    filename = filename.split('.').slice(0, -1).join('.')
  }
  if (!/^[\u4e00-\u9fa5_a-zA-Z0-9+-]+$/.test(filename)) {
    Message.error(
      `上传失败<文件名只能是中文、下划线、连字符、加号、数字、英文!>`,
    )
    setTimeout(() => {
      fileList.value = fileList.value.filter(f => {
        return !(
          file.lastModified === f.lastModified &&
          file.size === f.size &&
          file.name === f.name
        )
      })
    })
    return false
  }

  //重新上传的文件先过滤掉
  fileList.value = fileList.value.filter(({ originFileObj }) => {
    // console.log(
    //   file.lastModified,
    //   originFileObj.lastModified,
    //   file.size,
    //   originFileObj.size,
    //   file.name,
    //   originFileObj.name,
    //   file.webkitRelativePath,
    //   originFileObj.webkitRelativePath,
    // )
    return !(
      file.lastModified === originFileObj.lastModified &&
      file.size === originFileObj.size &&
      file.name === originFileObj.name
    )
  })
  emit('start')
  loading.value = true
  publishCount.value++
}
let onChange = info => {
  // setTimeout(() => {
  //   aaa.value.upload.abort()
  // }, 1000)
  if (info.file.status === 'done') {
    emit('end')
    loading.value = false
    publishCount.value--
    if (!info?.file?.response?.success) {
      Message.error(
        `上传失败<${info?.file?.response?.errorMessage || 'error'}>`,
      )
      return
    }
    // console.log(info)
    //获取上传后的id
    // info.file.dataId = info?.file?.response?.data

    //上传完毕后移除fileList的项，并且刷新发布列表
    fileList.value = fileList.value.filter(({ uid }) => uid !== info.file.uid)
    publishDrawerContentKey.value = Date.now()

    try {
      //刷新列表
      update()
    } catch (e) {}
  } else if (info.file.status === 'error') {
    emit('end')
    loading.value = false
    publishCount.value--
    Message.error(`上传失败<${info?.file?.error?.message || 'error'}>`)
  }
}
let headers = {
  Authorization: 'Bearer ' + account.token.value,
}
function dataCallback() {
  return {
    parentId: groupId.value,
    gmtBatchUpload: batchTime.value,
    ...props.params,
  }
}
/**
 * 设置上传批次时间
 */
let batchTime = ref()
function onClick() {
  batchTime.value = Date.now()
}
/**
 * 地址
 */
let dbType = useDbType()
let action =
  (!APP_MOCK_ENABLE ? import.meta.env.VITE_APP_API_BASE || '' : '') +
  rewriteURL('/data/ed/file/upload', dbType)
</script>
